<template>
  <el-row :gutter="20">
    <el-col :span="6">
      <el-card shadow="never" :body-style="{padding:'0px'}">
        <template #header>
          <div class="card-header">
            <span>角色列表</span>
            <el-button type="success" size="small" @click="doAdd">新增</el-button>
          </div>
        </template>
        <el-table :data="state.tableData" style="width: 100%" :row-class-name="doRowCLass(state.rowSelected)">
          <el-table-column prop="name" label="名称">
            <template #default="scope">
              <el-link @click="clickRoleRow(scope.row)" :underline="false">{{ scope.row.name}}</el-link>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="操作">
            <template #default="scope">
              <el-popconfirm
                  cancel-button-type="danger"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="confirmRoleDelete(scope.row,scope)"
                  title="确认删除吗?">
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete" class="card-small-btn"></el-button>
                </template>
              </el-popconfirm>
              <el-button type="success" size="small" icon="Edit" class="card-small-btn"
                         @click="doEdit(scope.row,scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-col>
    <el-col :span="18">
      <el-card shadow="never" :body-style="{padding:'0px'}">
        <template #header>
          <div class="card-header">
            <span>权限列表</span>
            <el-button v-if="state.rowSelected>0" type="success" size="small" @click="doSavePermission">保存</el-button>
          </div>
        </template>
        <div style="color:#d4d4d4;padding: 10px 5px; font-size: 13px;border-bottom: 1px solid #e4d7ed">
          提示：请先选择角色，然后在分配权限
        </div>
        <el-tree
            ref=permissionTree
            :data="state.permissionList"
            :show-checkbox="state.rowSelected>0"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :props="{ class: customNodeClass }"
        />
      </el-card>
    </el-col>
  </el-row>

  <el-dialog v-model="state.roleDialog.dialogVisible" :title="state.roleDialog.title" width="30%">
    <div>
      <el-form :model="state.roleDialog.form" label-width="80px">
        <el-form-item label="角色名称" :error="state.roleDialog.errors.name">
          <el-input v-model="state.roleDialog.form.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="state.roleDialog.doSubmitFunc" type="primary">提 交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script setup>

import {onMounted, reactive, ref} from "vue";
import _axios from "@/plugin/axios.js";
import {ElMessage} from "element-plus";


const state = reactive({
      tableData: [],
      roleDialog: {
        dialogVisible: false,
        title: "新增角色",
        form: {
          name: ''
        },
        errors: {
          name: ''
        },
        doSubmitFunc: doSubmit
      },
      editId: -1,
      editIndex: -1,
      permissionList: [],
      rowSelected:0
    }
)

const permissionTree = ref("")
onMounted(() => {
      initRole()
      initTotalPermission()
    }
)

function initRole() {
  _axios.get('api/rbac/role/').then((res) => {
    if (res.data.code === 0) {
      state.tableData = res.data.data
    } else {
      ElMessage.error("加载失败")
    }
  })
}

function initTotalPermission() {
  let context = [
    ]
  _axios.get('api/rbac/role/permission/').then((res) => {
    if (res.data.code === 0) {
      state.permissionList = res.data.data
    } else {
      ElMessage.error("加载失败")
    }
  })

}

function customNodeClass(data, node) {
  if (data.node_horizontal) {
    return 'is-horizontal'
  }
  return null
}

function doSavePermission() {
  let checkedList = permissionTree.value.getCheckedKeys(true)
  //console.log(permission_list)
  //permissionTree.value.setCheckedKeys([11, 12, 13])
  _axios.post(`/api/rbac/role/${state.rowSelected}/permission/`,{permission:checkedList}).then((res)=>{
    if (res.data.code===0){
      ElMessage.success("权限分配成功")
    }else{
      ElMessage.error("权限分配失败")
    }
  })

}

function confirmRoleDelete(row, scope) {
  _axios.delete(`api/rbac/role/${row.id}/`).then((res) => {
    if (res.data.code === 0) {
      // state.tableData.splice(scope.$index,1)
      state.tableData = state.tableData.filter((item) => {
        return item.id !== row.id
      })
      state.rowSelected=0
      permissionTree.value.setCheckedKeys([])
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
  })
}

function doEdit(row, idx) {
  state.roleDialog.dialogVisible = true
  state.roleDialog.title = "编辑角色"
  state.editId = row.id
  state.editIndex = idx
  // state.roleDialog.form = row
  for (let key in state.roleDialog.form) {
    state.roleDialog.form[key] = row[key]
  }
  state.roleDialog.errors = {}
}

function doAdd() {
  state.roleDialog.dialogVisible = true
  state.roleDialog.title = '新增角色'
  state.editId = -1
  state.editIndex = -1
  state.roleDialog.errors = {}
}

function doSubmit() {
  state.roleDialog.errors = {}
  if (state.editId > -1) {
    _axios.put(`/api/rbac/role/${state.editId}/`, state.roleDialog.form).then((res) => {
      if (res.data.code === 0) {
        state.tableData[state.editIndex] = res.data.data
        state.roleDialog.dialogVisible = false
        for (let key in state.roleDialog.form) {
          state.roleDialog.form[key] = ''
        }
        state.editId = -1
        state.editIndex = -1
      } else if (res.data.code === 2001) {
        for (let key in res.data.detail) {
          state.roleDialog.errors[key] = res.data.detail[key][0]
        }
      } else {
        ElMessage.error("编辑失败")
      }
    })
  } else {
    _axios.post("/api/rbac/role/", state.roleDialog.form).then((res) => {
      if (res.data.code === 0) {
        state.tableData.unshift(res.data.data)
        state.roleDialog.dialogVisible = false
        for (let key in state.roleDialog.form) {
          state.roleDialog.form[key] = ''
        }
      } else if (res.data.code === 2001) {
        for (let key in res.data.detail) {
          state.roleDialog.errors[key] = res.data.detail[key][0]
        }
      } else {
        ElMessage.error("添加失败")
      }
    })

  }

}

function clickRoleRow(row){
  state.rowSelected = row.id
  _axios.get(`/api/rbac/role/${row.id}/permission/`).then((res)=>{
    if (res.data.code===0){
      permissionTree.value.setCheckedKeys(res.data.data)
    }
  })
}

function doRowCLass(target){
  return function({row}){
    if (row.id === target){
      return "row-active"
    }
    return ""
  }

}
</script>

<style scoped>
.card-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;

}

.card-small-btn {
  padding: 0 2px;
  font-size: 12px;
  height: 18px;
  width: 18px;
}

</style>
<style>
.el-table .row-active {
  --el-table-tr-bg-color: var(--el-color-primary-light-9);
}
.el-table .row-active .el-link__inner{
  color: #409eff;
}
.is-horizontal > .el-tree-node__content {
  /*padding: 10px 0;*/
}

.el-tree .el-tree-node.is-horizontal > .el-tree-node__children {
  display: flex;
  flex-direction: row;
}

.is-horizontal > .el-tree-node__children > div {
  width: 90%;
}
</style>